//
//  CreateGroupViewController.m
//  SouthChina
//
//  Created by zorro on 15/6/30.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "CreateGroupViewController.h"
#import "CreateGroupView.h"
#import "UnitView.h"
#import "selectMemberViewController.h"
#import "selectAllGroupViewController.h"
#import "selectLabelViewController.h"
#import "DataDict.h"
#import "AddressBookViewController.h"
@interface CreateGroupViewController ()<UnitViewDelegate,UITextFieldDelegate>
{
    CreateGroupView * viewBody;
}

@end

@implementation CreateGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleBarWithBackBtn:@"创建群" needReturn:TRUE];
    
    /*记得初始化一些成员变量*/
    /*传递参数时，记得初始化变量的值*/
    _superGroup = [[NSMutableDictionary alloc]init];
    _selectedLable = [[NSMutableSet alloc]init];
    
    //导航栏上面的完成按钮
     UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     rightBtn.frame = CGRectMake(270.0f, (YNEW)+2, 50.0f, 40.0f);
     [rightBtn setTitle:@"完成" forState: UIControlStateNormal];
     
     [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
     rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
     
     [self.titlebar addSubview:rightBtn];
    
    viewBody = [[[NSBundle mainBundle] loadNibNamed:@"CreateGroupViewBody" owner:self options:nil] objectAtIndex:0];
    //20151010
    viewBody.txtGroupName.delegate = self;
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    
    viewBody.groupUser.isAddButton =YES;
    //很变态的一个地方，xib上面画的UnitView根本没有自动初始化，这里重新初始化一次才行。
    viewBody.groupUser = [viewBody.groupUser initWithFrame:viewBody.groupUser.frame];
    viewBody.groupUser.delegate = self;
    //刷新viewBody.groupUser 数据   
    
    viewBody.groupTypeSwitch.enabled = NO;
    [self.view addSubview:viewBody];
    
    _selectedContact = [[NSMutableSet alloc] init];
}

//20151010
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"DAFASFASFA");
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [viewBody.groupUser removeAll];
    
    //NSLog(@"viewBody.groupUser------%lu",viewBody.groupUser.)
    for( Contact * contact in _selectedContact)
    {
        [viewBody.groupUser addNewUnit:contact];
    }
    
    if([_superGroup objectForKey:@"groupName"] !=nil)
    {
        viewBody.btnSuperGroup.titleLabel.text = [_superGroup objectForKey:@"groupName"];
    }
}

/*!
 *  点击选择的成员，进行数据清理
 *
 *  @param unitCell <#unitCell description#>
 */
- (void) extendCellTouched:(UnitCell *)unitCell
{
    if(unitCell.tag == ADDTAG)
    {
        NSLog(@"点击增加成员");
        selectMemberViewController * selectMember = [[selectMemberViewController alloc] init];
        selectMember.selectedContact  = _selectedContact;
        selectMember.CreateType =  CREATETYPE_CREATEGROUP;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:selectMember animated:NO];
    }
    
    //点击选择好的成员后，需要清理数据
    Contact *contact =unitCell.contact;
    
    for (Contact * i   in  _selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [_selectedContact removeObject:i];
            break;
        }
    }
}

-(void)showRightBtnView:(id)sender
{
    //自动收键盘由于收起键盘动画需要时间，所以会在上个界面有个闪影
    [viewBody.txtGroupName resignFirstResponder]; //键盘隐藏
    
    NSString * groupName =  viewBody.txtGroupName.text;
    //20151010
    if(groupName ==nil || groupName.length <2 || groupName.length>10)
    {
        [self showAlerHUD:@"请输入2-10个字的群名称！"];
        return;
    }
    if(_selectedContact.count >200)
    {
        [self showAlerHUD:@"添加的群成员人数不能大于200人"];
        return;
    }
    
    
    /*"groupType":"1", --群组类型1 普通群 2 行政群 3 讨论组
     "userIds":"9004,9005,9006",--添加的用户列表，用逗号隔开 选填
     "groupName":"信网中心群",--群名称 选填
     "groupTags":"72,73,81",--群标签，多个值用逗号隔开 选填
     "toMountGroupId":"10000736",--挂靠的群组Id选填*/
        
    NSEnumerator *enumerator = [_selectedContact objectEnumerator];
    NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
    [ids insertString:[NSString stringWithFormat:@"%@,",DE.userId] atIndex:0];
    NSLog(@"%@",ids);
    for (Contact *cid in enumerator) {
        [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
         NSLog(@"****%@",ids);
    }
    
    NSEnumerator *enumeratorLable = [_selectedLable objectEnumerator];
    NSMutableString *idsLable = [[NSMutableString alloc] initWithString:@""];
    for (DataDict *cid in enumeratorLable) {
        [idsLable insertString:[NSString stringWithFormat:@"%@,",cid.dictdataId] atIndex:0];
    }
    
    NSString * toMountGroupId = [_superGroup objectForKey:@"groupId"];
    if(toMountGroupId == nil) toMountGroupId =@"";
    
    NSLog(@"创建群成员id列表%@",ids);
    //暂时把挂靠群功能禁掉
    
    NSDictionary *dict  = @{@"groupType":@"1",
                            @"userIds":ids,
                            @"groupName":groupName,
                            @"groupTags":idsLable,
                            @"toMountGroupId":toMountGroupId};
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"createGrp" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (success) {
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                        [view show];
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"创建群组失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"创建群组失败！"];
                    
                }
                
            }];
            
        }else{
            
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
            [view show];
        }
        
    }];

}

- (IBAction)clickSuperGroup:(id)sender {
    //进入选择上级群页面
    selectAllGroupViewController * select = [[selectAllGroupViewController alloc] init];

    select.superGroup  = _superGroup;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:select animated:NO];
}
- (IBAction)clickSelectLable:(id)sender {
    selectLabelViewController * select = [[selectLabelViewController alloc] init];
        
    select.selectedLable  = _selectedLable;
    select.sLableType = GROUP_LABLE;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:select animated:NO];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
     /*kAppDelegate.needRefrsh=YES;
     [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
    */
    //此语句为了解决键盘闪现的问题，键盘收回时展示需要时间
   [self performSelector:@selector(popToRootVC) withObject:nil afterDelay:0.25];
    
}

-(void)popToRootVC
{
    kAppDelegate.needRefrsh=YES;
    [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
